/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlet;

import com.gr.context.ContextManager;
import com.gr.context.Profile;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gr.search.*;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Binh
 */
public class result extends HttpServlet {

    String ip = "123.24.204.18";

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
             out.println("<html>");
             out.println("<head>");
             out.println("<title>Servlet result</title>");  
             out.println("</head>");
             out.println("<body>");
             out.println("<h1>Servlet result at " + request.getContextPath () + "</h1>");
             out.println("</body>");
             out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            response.setContentType("text/html;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            HttpSession session = request.getSession(false);
            ContextSearcher cs;
            if (session != null) {
                cs = new ContextSearcher((int) session.getAttribute("id"), "193.11.107.38");
            } else {
                cs = new ContextSearcher(1, ip);
            }
            String que = request.getParameter("txt_query");
            if (que == null) {
                que = " ";
            }
            String type = request.getParameter("search_type");
            if (session == null) {
                type = "txt_noncontext";
            }
            String cluster = request.getParameter("cluster");
            if (session == null) {
                cluster = "txt_noncluster";
            }
            System.out.println(cluster);
            PrintWriter out = response.getWriter();
            out.println("<HTML>");
            out.println("<HEAD><meta  http-equiv='Content-Type'  content='text/html; "
                    + "charset=UTF-8'/><TITLE>Context-based IRS</TITLE><link href=\"\" "
                    + "rel=\"stylesheet\" type=\"text/css\" /></HEAD>");
            //out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
            out.println("<BODY>");
            out.println("<div id=\"form\" name=\"form\" style=\"background-color: #e9e5e5;"
                    + "padding-top:30px;height:100px;text-align:center\">");
            out.println("<form method=post name=\"search2\" action=\"result\">");
            out.println("<p><input type=\"text\" value=\"" + que + "\" name=\"txt_query\" "
                    + "id=\"txt_query\" style=\"width:450px;	height:30px;font-size: large;\">"
                    + " <input type=\"submit\" value=\"Search\"></p>");
            if (session != null) {
                out.println("<input type=\"radio\" name=\"search_type\" id=\"txt_context\" "
                        + "value=\"txt_context\" checked=\"checked\"/>Context-based search"
                        + "<input type=\"radio\" name=\"search_type\" id=\"txt_noncontext\" value=\"txt_noncontext\" />Non-context-based search");
                out.println("<input type=\"radio\" name=\"cluster\" id=\"txt_non cluster\" "
                        + "value=\"txt_noncluster\" checked=\"checked\"/>Non-cluster results"
                        + "<input type=\"radio\" name=\"cluster\" id=\"txt_cluster\" value=\"txt_cluster\" />Cluster results");
            }
            out.println("</form>");
            out.println("</div>");
            if (session != null) {
                int id = (int) session.getAttribute("id");

//             ContextManager cm=new ContextManager(id,"123.24.204.18"); 
                ContextManager cm = new ContextManager(id, ip);
                out.println("<div id=\"left_content\" style=\"padding-left:5px;margin_top:10px;"
                        + "float:left;width:18%\"><table><tr><td>Xinc chào: </td><td><b>" + cm.getProfile().getName() + " </b></td></tr><tr><tr><td>Vị trí :</td><td>" + cm.getLocation().city + "</td></tr><tr><td></td><td><form method =\"post\" action=\"sign_out\"> <input type=\"submit\" value=\"Thoát\"></form></td></tr></table><hr>");
                String[] interestList = cm.getProfile().getInterest();
                out.println("<b>Sở thích chính</b><br>");
                for (int i = 0; i < interestList.length; i++) {
                    if (interestList[i] != null) {
                        out.println(interestList[i] + "<br>");
                    }
                }

                out.println("<hr></div>");
            } else {
                out.println(" <div id=\"left_content\" style=\"padding-left:5px;margin_top:10px;float:left;width:18%\"><form  name=\"login_form\" method=\"post\" action=\"login_action\"><table align=\"center\"><tr><td>Username</td><td><input type=\"text\" id=\"txt_user\" name=\"txt_user\"/></td></tr><tr style=\"padding-top: 5px\"><td>Password</td><td><input type=\"password\" id=\"txt_pass\" name=\"txt_pass\"/></td></tr> <tr><td></td><td><button type=\"submit\" id=\"login\" name=\"login\">Login</button></td></tr></table></form><a href=\"Signup.html\">Đăng ký tài khoản mới</a><hr></hr></div>   ");
            }
            out.println("<div id=\"display\" name=\"display\" style=\"padding-left: 5px;padding-top:30px; padding-right:20px;float:right;width:77%;font-size:large\">");
            try {
                String buf;
                if (type.compareTo("txt_context") != 0) {
                    buf = cs.search(que, 0, 0);
                } else if (cluster.compareTo("txt_cluster") == 0) {
                    buf = cs.search(que, 1, 1);
                } else {
                    buf = cs.search(que, 1, 0);
                }
                out.println(buf);
            } catch (Exception ex) {
                ex.getStackTrace().toString();
            }
            out.println("</div>");
            out.println("</BODY></HTML>");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Handles the query log writer
     */
//    public void hyperlinkUpdate(HyperlinkEvent e) {
//        HyperlinkEvent.EventType type = e.getEventType();
//         String des = e.getDescription();
//
//        if (type == HyperlinkEvent.EventType.ACTIVATED)
//            try {
//            jTextField2.setText(des);
//            File openAs = new File(des);
//            FileReader in = new FileReader(openAs);
//            jTextArea1.read(in, openAs.toString());
//            ql.increaseClickedTime();
//            ql.addClickedFile(des);
//            System.out.println("update hyperlink");
//            System.out.println(ql.QueryLogToString());
//           //throw new UnsupportedOperationException("Not supported yet.");
//        //throw new UnsupportedOperationException("Not supported yet.");
//        } catch (IOException ex) {
//            Logger.getLogger(SearchJFrame.class.getName()).log(Level.SEVERE, null, ex);
//        }
//    }
    /**
     * Handles the search process
     */
    public static void getIPstr() throws Exception {
    }
    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
}
